﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        // 下面的代码块被编译后，会自动生成‘TV’属性，并为该属性添加get set方法
        public TreeView TV
        {
            get;
            set;
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            MessageBox.Show("Form2_Load");
            if (TV != null)
            {

                //foreach (Control ctl in Controls)
                //{
                //    TreeNode tn = new TreeNode(ctl.Name);
                //    TV.Nodes.Add(tn);
                //    foreach (Control ctlChild in ctl.Controls)
                //    {
                //        TreeNode tnChild = new TreeNode(ctlChild.Name);
                //        tn.Nodes.Add(tnChild);
                //    }
                //}
                TreeNode tnRoot = new TreeNode(this.Name);
                // FormMain.cs中有代码‘frm.TV = treeView1;’所以此处的TV即主窗口中的treeView1
                TV.Nodes.Add(tnRoot);
                RecursiveControls(this, tnRoot);
                TV.ExpandAll();
            }
        }

        void RecursiveControls(Control ctlParent, TreeNode tnParent)
        {
            foreach (Control ctl in ctlParent.Controls)
            {
                TreeNode tn = new TreeNode(ctl.Name);
                // tn.Tag指向当前控件ctl，结点要与控件对应
                tn.Tag = ctl;
                tnParent.Nodes.Add(tn);
                RecursiveControls(ctl, tn);
            }
        }

    }
}
